<template>
  <div class="mark-company-gcp">
    <SearchBar v-if="props.visible" close-enter closePlan closeAdvanced>
      <template #footer>
        <el-button type="primary" @click="Object.assign(modalState, { type: 'add', data: {}, visible: true })">
          {{ $t("marking_company.add_gcp") }}
        </el-button>
      </template>
    </SearchBar>
    <div class="merak-table-wrapper">
      <MerakXTable
        ref="tableRef"
        v-bind="tableState"
        :params="tableParams"
        :query-columns="handleQueryColumns"
        :query-data="handleQueryData"
      ></MerakXTable>
    </div>
    <el-dialog v-model="modalState.visible" destroy-on-close :title="modalTitle" :width="500" @closed="handleClose">
      <el-form ref="formRef" label-position="top" :model="modalState.data" :rules="formRules">
        <el-form-item prop="gcp" :label="$t('marking_company.gcp')">
          <el-input v-model="modalState.data.gcp" v-num class="qf_input" :maxlength="200" />
        </el-form-item>
        <el-form-item prop="serial_start" :label="$t('marking_company.serial_start')">
          <el-input v-model="modalState.data.serial_start" v-num class="qf_input" :maxlength="15" />
        </el-form-item>
        <el-form-item prop="serial_end" :label="$t('marking_company.serial_end')">
          <el-input v-model="modalState.data.serial_end" v-num class="qf_input" :maxlength="15" />
        </el-form-item>
      </el-form>
      <div class="mark-company-gcp--handle">
        <el-button @click="modalState.visible = false">{{ $t("merak.cancel") }}</el-button>
        <el-button type="primary" plain :loading="modalState.resetLoading" @click="handleSave(true)">
          {{ $t("merak.save_continue") }}
        </el-button>
        <el-button type="primary" :loading="modalState.loading" @click="handleSave()">{{ $t("merak.save") }}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { getCurrentInstance, ref, reactive, computed } from "vue";

import { FormRules, ElButton, ElDialog, ElForm, ElFormItem, ElInput, ElMessage } from "element-plus";

import SearchBar from "@/components/SearchBar/index.vue";

import MerakXTable, { MerakXTableInstance, MerakXTableProps } from "@/components/MerakXTable";

import { ResultEnum } from "@/enums/httpEnum";
import { getGCPTableColumns, getGCPTableData, saveGCP } from "@/api/modules/markingManagement/company";

const props = defineProps<{ visible: boolean; data: Record<string, any> }>();

const currentInstance = getCurrentInstance();

const tableRef = ref<MerakXTableInstance>();

const formRef = ref<InstanceType<typeof ElForm>>();

// 保存状态
const saved = ref(false);

// 表格属性
const tableState = reactive<MerakXTableProps>({
  columnsByStore: [],
  showHeader: false
});

// 弹窗相关数据
const modalState = reactive<{
  type?: "add" | "edit";
  data: Record<string, any>;
  visible: boolean;
  loading: boolean;
  resetLoading: boolean;
}>({
  data: {},
  visible: false,
  loading: false,
  resetLoading: false
});

// 表格外部搜索条件
const tableParams = computed(() => ({
  import_company_id: props.data.import_company_id
}));

// 弹窗标题
const modalTitle = computed(() =>
  modalState.type === "add"
    ? currentInstance?.proxy?.$t("marking_company.add_gcp")
    : modalState.type === "edit"
      ? modalState.data.gcp
      : ""
);

// 表单校验
const formRules = computed<FormRules>(() => ({
  gcp: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!!value) {
          if (value.length < 5) {
            callback(new Error(currentInstance?.proxy?.$t("marking_company.gcp_valid_limit")));
          } else {
            callback();
          }
        } else {
          callback(new Error(currentInstance?.proxy?.$t("marking_company.gcp_valid")));
        }
      }
    }
  ],
  serial_start: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!!Number(value)) {
          if (!!Number(modalState.data.serial_end) && Number(modalState.data.serial_end) <= Number(value)) {
            callback(new Error(currentInstance?.proxy?.$t("marking_company.serial_start_valid_limit")));
          } else {
            callback();
          }
        } else {
          callback(new Error(currentInstance?.proxy?.$t("marking_company.serial_start_valid")));
        }
      }
    }
  ],
  serial_end: [
    {
      required: true,
      validator: (rule, value, callback) => {
        if (!!Number(value)) {
          if (!!Number(modalState.data.serial_start) && Number(modalState.data.serial_start) >= Number(value)) {
            callback(new Error(currentInstance?.proxy?.$t("marking_company.serial_end_valid_limit")));
          } else {
            callback();
          }
        } else {
          callback(new Error(currentInstance?.proxy?.$t("marking_company.serial_end_valid")));
        }
      }
    }
  ]
}));

// 请求表格头部
const handleQueryColumns: MerakXTableProps["queryColumns"] = async () => {
  return await getGCPTableColumns({ import_company_id: props.data.import_company_id }).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      tableState.columnsByStore = JSON.parse(JSON.stringify(data.columns));
      return {
        ...data,
        columns: data.columns.map(col => {
          switch (col.field) {
            case "gcp":
              col.fixed = "left";
              break;

            default:
              break;
          }
          return { ...col };
        })
      };
    }
  });
};

// 请求列表数据
const handleQueryData: MerakXTableProps["queryData"] = async ({ page, from }) => {
  const params: Record<string, any> = {};
  if (!!from) {
    Object.assign(params, from);
  }
  return await getGCPTableData(params).then(({ code, data }) => {
    if (code == ResultEnum.SUCCESS) {
      return { ...data.table_data };
    }
  });
};

// 表单提交
const handleSave = (reset: boolean = false) => {
  formRef.value?.validate().then(() => {
    if (reset) {
      modalState.resetLoading = true;
    } else {
      modalState.loading = true;
    }
    saveGCP({ ...modalState.data, import_company_id: props.data.import_company_id }).then(({ code, message }) => {
      if (reset) {
        modalState.resetLoading = false;
      } else {
        modalState.loading = false;
      }
      if (code == ResultEnum.SUCCESS) {
        saved.value = true;
        if (reset) {
          formRef.value?.resetFields();
        } else {
          modalState.visible = false;
        }
        ElMessage.success(currentInstance?.proxy?.$t("marking_company.add_gcp_success"));
      } else {
        const msg = typeof message === "object" ? Object.values(message)?.[0] : message;
        ElMessage.error(msg);
      }
    });
  });
};

// 弹窗关闭刷新列表
const handleClose = () => {
  if (saved.value) {
    tableRef.value?.reloadData();
    saved.value = false;
  }
};
</script>

<style scoped lang="scss">
.mark-company-gcp {
  display: flex;
  flex-direction: column;
  height: 100%;
  .search_bar + .merak-table-wrapper {
    margin-top: var(--merak-padding);
  }
}

.mark-company-gcp--handle {
  margin-top: var(--merak-padding);
  text-align: right;
}
</style>
